package com.thinkfit.jy.activity;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.lib.activity.BaseActivity;
import com.common.lib.bean.BannerBean;
import com.common.lib.bean.ProceduralTrainBean;
import com.common.lib.bean.VersionBean;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.thinkfit.jy.R;
import com.thinkfit.jy.bluetooth.Bluetooth;
import com.thinkfit.jy.contract.MainContract;
import com.thinkfit.jy.presenter.MainPresenter;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.FastBlurUtility;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainADActivity extends BaseActivity<MainContract.Presenter> implements MainContract.View {

    private Disposable mDisposableCountDown;
    protected boolean mIsMainActivity = false;
    private AudioManager mAudioManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_ad;
    }

    @Override
    protected void onCreated(@Nullable Bundle savedInstanceState) {
        init();
    }

    public void onResume() {
        super.onResume();
        showUserInfo();
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        showBottomUI();
    }


    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("ddddddddddddddddddddddd   MainADActivity ");
        DeviceTypeUtils.showBackButton(getApplicationContext());
    }

    protected void showBottomUI() {
        setImage(R.id.ivBluetooth, Bluetooth.getInstance().isBluetoothOpened() ?
                R.drawable.app_bluetooth_open_ad : R.drawable.app_bluetooth_close_ad);

        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String ssid = wifiInfo.getSSID().replace("\"", "");
        setImage(R.id.ivWifi, ssid.equals("<unknown ssid>") ?
                R.drawable.app_wifi_close_ad : R.drawable.app_wifi_open_ad);

        resetVoiceUI((int) (getAudioManager().getStreamVolume(AudioManager.STREAM_MUSIC) * 100f / getAudioManager().getStreamMaxVolume(AudioManager.STREAM_MUSIC)));
    }

    public void showUserInfo() {
    }

    public void init() {
        mIsMainActivity = true;
        setViewsOnClickListener(R.id.ivWifi, R.id.ivSound, R.id.ivBluetooth);
        startTimer();
        resetDate();
        getPresenter().getAdvert();
    }


    @NonNull
    @Override
    protected MainContract.Presenter onCreatePresenter() {
        return new MainPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivSound:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                Bundle bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, 1);
                openActivity(SoundActivity.class, bundle);
                break;
            case R.id.ivBluetooth:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, 1);
                openActivity(SettingActivity.class, bundle);
                break;
            case R.id.ivHome:
                toHomeActivity();
                break;
            case R.id.ivSetting:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                openActivity(SettingActivity.class);
                //     overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if (map.containsKey(EventBusEvent.START_RUN)) {
            int count = (int) map.get(EventBusEvent.START_RUN);
            if (count > 0 && isOnResume()) {
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                Bundle bundle = new Bundle();
                bundle.putInt(Constants.BUNDLE_EXTRA, count);
                openActivity(CountDownActivity.class, bundle);
            }
        } else if (map.containsKey(EventBusEvent.BLUETOOTH_CHANGE)) {
            setImage(R.id.ivBluetooth, (boolean) map.get(EventBusEvent.BLUETOOTH_CHANGE) ?
                    R.drawable.app_bluetooth_open_ad : R.drawable.app_bluetooth_close_ad);
        } else if (map.containsKey(EventBusEvent.VOICE_CHANGE)) {
            resetVoiceUI((int) map.get(EventBusEvent.VOICE_CHANGE));
        }  else {
            super.onReceive(map);
        }
    }

    private void resetVoiceUI(int voiceValue) {
        if (voiceValue < 20) {
            setImage(R.id.ivSound, R.drawable.app_sound_0_ad);
        } else if (voiceValue < 60) {
            setImage(R.id.ivSound, R.drawable.app_sound_1_ad);
        } else {
            setImage(R.id.ivSound, R.drawable.app_sound_2_ad);
        }
    }


    private void startTimer() {   //做一个全局倒计时显示时间
        if (mDisposableCountDown != null) {
            mDisposableCountDown.dispose();
        }
        mDisposableCountDown = Observable.intervalRange(1, Long.MAX_VALUE, 500, 1, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put(EventBusEvent.TIME_CHANGE, "");
                        EventBus.getDefault().post(map);  //时间变化通知其他页面

                        int type = DataManager.Companion.getInstance().getScreenTime();
                        if (type == 0) {  //没有屏保
                            return;
                        }
                        long dTime = 0L;
                        switch (type) {
                            case 1:
                                dTime = 60 * 1000L;
                                break;
                            case 2:
                                dTime = 3 * 60 * 1000L;
                                break;
                            case 3:
                                dTime = 5 * 60 * 1000L;
                                break;
                            case 4:
                                dTime = 15 * 60 * 1000L;
                                break;
                            case 5:
                                dTime = 30 * 60 * 1000L;
                                break;
                        }

                        long lastTapTime = DataManager.Companion.getInstance().getTapTime();

                        if (lastTapTime > 0L && System.currentTimeMillis() - lastTapTime > dTime) {
                            DataManager.Companion.getInstance().saveTapTime(System.currentTimeMillis());
                            openActivity(ScreenProtectActivity.class);
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        resetDate();
                    }
                });
    }

    public void onDestroy() {
        super.onDestroy();
        if (mDisposableCountDown != null) {
            mDisposableCountDown.dispose();
        }
    }

    public void resetDate() {
        Calendar now = Calendar.getInstance();
        if (now.get(Calendar.AM_PM) == Calendar.AM) {
            setText(R.id.tvCurrentTime, BaseUtils.StaticParams.getNewText(now.get(Calendar.HOUR_OF_DAY))
                    + ":" + BaseUtils.StaticParams.getNewText(now.get(Calendar.MINUTE)) + " " + getString(R.string.app_am));
        } else {
            setText(R.id.tvCurrentTime, BaseUtils.StaticParams.getNewText(now.get(Calendar.HOUR_OF_DAY) - 12)
                    + ":" + BaseUtils.StaticParams.getNewText(now.get(Calendar.MINUTE)) + " " + getString(R.string.app_pm));
        }
        int month = now.get(Calendar.MONTH) + 1;
        int day = now.get(Calendar.DAY_OF_MONTH);
        int weekDay = now.get(Calendar.DAY_OF_WEEK);
        setText(R.id.tvDate, BaseUtils.StaticParams.getNewText(month) + getString(R.string.app_month) + BaseUtils.StaticParams.getNewText(day) + getString(R.string.app_day) +
                getString(getResources().getIdentifier("app_weekday_" + weekDay, "string", getPackageName())));
    }

    @Override
    public boolean isMainActivity() {
        return true;
    }

    @Override
    public void getAdvertSuccess(ArrayList<BannerBean> list) {

    }

    @Override
    public void getVersionSuccess(VersionBean bean) {

    }

    @Override
    public void getVideoListSuccess(ProceduralTrainBean bean) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBroadcastReceive(Intent intent) {
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (state) {
                case WifiManager.WIFI_STATE_DISABLED: {
                    setImage(R.id.ivWifi, R.drawable.app_wifi_close_ad);
                    break;
                }
                case WifiManager.WIFI_STATE_DISABLING: {
                    Log.d(TAG, "正在关闭");
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLED: {
                    setImage(R.id.ivWifi, R.drawable.app_wifi_open_ad);
                    break;
                }
                case WifiManager.WIFI_STATE_ENABLING: {
                    Log.d(TAG, "正在打开");
                    break;
                }
                case WifiManager.WIFI_STATE_UNKNOWN: {
                    Log.d(TAG, "未知状态");
                    break;
                }
            }
        }
    }

    private AudioManager getAudioManager() {
        if (mAudioManager == null) {
            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        }
        return mAudioManager;
    }
}